<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>TTS在线阅读</title>
  <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
  <textarea name="" id="text" cols="30" rows="10">
  此处输入要阅读内容，
  我的TTS，希望你能喜欢</textarea><a href="" id="readit">开始阅读</a>
  <audio controls="" autoplay="" name="media" id="audio">
    <source src="http://tts.baidu.com/text2audio?idx=1&tex=%25E6%25AC%25A2%25E8%25BF%258E%25E4%25BD%25BF%25E7%2594%25A8%25E5%259C%25A8%25E7%25BA%25BFTTS%25EF%25BC%2581&cuid=baidu_speech_demo&cod=2&lan=zh&ctp=1&pdt=1&spd=5&per=0&vol=5&pit=5" type="audio/mp3">
  </audio>
  <script>
    $(function() {
      var $text = $('#text'),
          text = "",
          $audio = $('#audio'),
          audiom = $audio.get(0),
          textA = [],
          textAlen = 0,
          et = 0,
          i = -1;

      $('#readit').on('click', function(event) {
        event.preventDefault();
        text = $.trim($text.val());
        textA = text.split(/\s+/);
        textAlen = textA.length;
        i = 0;
        audiom.src = getUrl(textA[i]);
        audiom.load();
      });

      /*$text.on('focus', function(event) {
        audiom.pause();
      });*/
      
      function getUrl(t) {
        var decodeTxt = encodeURIComponent(t);
        return 'http://tts.baidu.com/text2audio?idx=1&tex=' + decodeTxt +'&cuid=baidu_speech_demo&cod=2&lan=zh&ctp=1&pdt=1&spd=5&per=0&vol=8&pit=5';
      }
      audiom.addEventListener('ended', function() {
        if (i === -1) {
          return false;
        }
        var thisText = textA[++i];
        if (i < textAlen) {
          if (thisText.length === 1) {
            thisText = textA[++i];
          }
          audiom.src = getUrl(thisText);
          audiom.load();
        } else {
          if (et === 3) {
            et = 0;
            return false;
          }
          audiom.src = 'http://tts.baidu.com/text2audio?idx=1&tex=%25E8%25AF%25BB%25E5%25AE%258C%25E4%25BA%2586&cuid=baidu_speech_demo&cod=2&lan=zh&ctp=1&pdt=1&spd=5&per=0&vol=9&pit=5';
          audiom.load();
          et++;
        }
      }, false);
    });
  </script>
</body>
</html>